package ar.edu.uba.fi.jmit.aspecter.monitor.fieldValue;

import java.util.HashMap;
import java.util.Map;

import javassist.expr.Expr;
import ar.edu.uba.fi.jmit.aspecter.core.Constants;
import ar.edu.uba.fi.jmit.aspecter.core.CoreUtils;
import ar.edu.uba.fi.jmit.aspecter.core.ResourceProperties;
import ar.edu.uba.fi.jmit.aspecter.core.interceptor.FieldAccessInterceptor;
import ar.edu.uba.fi.jmit.aspecter.core.interceptor.FieldAccessType;
/**
 * Interceptor para el tipo de monitoreo "Valor de un Atributo de un Objeto"
 * @author Tomas
 *
 */
public class FieldValueFieldAccessInterceptor extends FieldAccessInterceptor {
	
	/**
	 * Nombre de este monitor
	 */
	private String monitorName;
	/**
	 * Prioridad de este monitor
	 */
	private String priority = ResourceProperties.getProperty(Constants.EVENT_DEFAULT_PRIORITY);
	
	/**
	 * Tiene que tener al menos el mismo nivel de visibilidad que el field
	 */
	private String idObject;

	public FieldValueFieldAccessInterceptor(String className, String fieldName, String monitorName, String idObject) {
		super(className, fieldName, FieldAccessType.WRITE);
		this.monitorName = monitorName;
		this.idObject = idObject;
	}
	
	public FieldValueFieldAccessInterceptor(String className, String fieldName, String monitorName, String idObject, String priority) {
		this(className, fieldName, monitorName, idObject);
		this.priority = priority;
	}

	@Override
	protected String aspectStatementAfter() {
		StringBuffer buff = new StringBuffer();
 		Map<String, String> dataMap = new HashMap<String, String>();
 		dataMap.put(ResourceProperties.getProperty(Constants.EVENT_MONITOR_NAME_KEY), "\"" + monitorName + "\"");
 		dataMap.put(ResourceProperties.getProperty(Constants.EVENT_ID_OBJECT_KEY), "(java.io.Serializable)(($w)$0." + idObject + ")");
 		dataMap.put(ResourceProperties.getProperty(Constants.EVENT_MONITOR_DATE), "new java.util.Date()");
 		dataMap.put(ResourceProperties.getProperty(Constants.FIELD_NEW_VALUE), "(java.io.Serializable)($w)$1");
 		CoreUtils.createEventCode(buff, priority, getSource(), dataMap, true);
		return buff.toString();
	}
	
	/**
	 * Devuelve el texto que va a ser enviado como "source" en los eventos al monitorEngine
	 * @return
	 */
	protected String getSource() {
		return "this.toString()";
	}

	@Override
	protected String aspectStatementBefore() {
		return "";
	}

	@Override
	public boolean mustAspect(Expr expression) {
		return true;
	}

}
